package com.zhao.fishingguideserver.controller;

import com.zhao.fishingguideserver.POJO.Result;
import com.zhao.fishingguideserver.POJO.User;
import com.zhao.fishingguideserver.dto.RegisterRequest;
import com.zhao.fishingguideserver.utils.JwtUtil;
import com.zhao.fishingguideserver.utils.Md5Util;
import com.zhao.fishingguideserver.utils.ThreadLocalUtil;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.zhao.fishingguideserver.service.UserService;
import java.util.HashMap;
import java.util.Map;

// 关键：添加/api前缀，与前端请求路径（/api/user/login）一致
@RestController
@Validated
@RequestMapping("/user")
public class UserController {
    @Autowired
    UserService userService; // 变量名规范：首字母小写（原UserService UserService）

    @PostMapping("/register")
    public Result register(@RequestBody @Valid RegisterRequest registerRequest){
        User u = userService.selectUserByName(registerRequest.getUsername());
        if(u == null){
            // 需要将 RegisterRequest 转换为 User 对象
            User user = new User();
            user.setUsername(registerRequest.getUsername());
            // 密码加密（与登录时的Md5Util.checkPassword对应）
            user.setPassword(Md5Util.getMD5String(registerRequest.getPassword()));
            userService.register(user);
            return Result.success();
        }
        else return Result.error("用户已存在");
    }

    @PostMapping("/login")
    public Result<Map<String, String>> login(@RequestBody @Valid User user) {
        // 1. 根据用户名查询数据库用户
        User dbUser = userService.selectUserByName(user.getUsername());
        System.out.println(dbUser.getUser_id());
        if (dbUser == null) {
            return Result.error("用户不存在！");
        }

        // 2. 验证密码（前端未加密时，此处需用Md5Util加密后对比）
        if (Md5Util.checkPassword(user.getPassword(), dbUser.getPassword())) {
            // 3. 生成JWT Token（存用户id和username，不存密码！）
            Map<String, Object> claims = new HashMap<>();
            claims.put("id", dbUser.getUser_id());// 存User的userId（Long类型）
            claims.put("username", dbUser.getUsername());
            // 注意：不要存密码！！！（安全风险）
            String token = JwtUtil.genToken(claims);
            System.out.println("生成的Token:" + token);
            
            // 返回包含token的Map对象，符合前端期望的数据格式
            Map<String, String> data = new HashMap<>();
            data.put("token", token);
            return Result.success(data);
        } else {
            return Result.error("密码错误！");
        }
    }

    /**
     * 获取当前登录用户信息
     */
    @PostMapping("/userInfo")
    public Result<User> getUserInfo() {
        Map<String, Object> claims = ThreadLocalUtil.get();
        if (claims == null || claims.get("id") == null) {
            return Result.error("用户未登录");
        }
        String username = (String) claims.get("username");
        User user = userService.selectUserByName(username);
        return Result.success(user);
    }

    /**
     * 更新用户信息
     */
    @PutMapping("/update")
    public Result<String> updateUserInfo(@RequestBody User user) {
        Map<String, Object> claims = ThreadLocalUtil.get();
        if (claims == null || claims.get("id") == null) {
            return Result.error("用户未登录");
        }
        Long userId = Long.parseLong(claims.get("id").toString());
        
        // 设置用户ID，防止修改他人信息
        user.setUser_id(userId);
        
        int result = userService.updateUser(user);
        return result > 0 ? Result.success("用户信息更新成功") : Result.error("用户信息更新失败");
    }

    /**
     * 修改密码
     */
    @PutMapping("/updatePassword")
    public Result<String> updatePassword(
            @RequestParam String oldPassword,
            @RequestParam String newPassword
    ) {
        Map<String, Object> claims = ThreadLocalUtil.get();
        if (claims == null || claims.get("id") == null) {
            return Result.error("用户未登录");
        }
        String username = (String) claims.get("username");

        // 验证旧密码
        User user = userService.selectUserByName(username);
        if (!Md5Util.checkPassword(oldPassword, user.getPassword())) {
            return Result.error("原密码错误");
        }

        // 更新密码
        user.setPassword(Md5Util.getMD5String(newPassword));
        int result = userService.updateUser(user);
        return result > 0 ? Result.success("密码修改成功") : Result.error("密码修改失败");
    }

    /**
     * 更新昵称
     */
    @PutMapping("/updateNickname")
    public Result<String> updateNickname(@RequestParam String nickName) {
        Map<String, Object> claims = ThreadLocalUtil.get();
        if (claims == null || claims.get("id") == null) {
            return Result.error("用户未登录");
        }
        Long userId = Long.parseLong(claims.get("id").toString());

        User user = new User();
        user.setUser_id(userId);
        user.setNickName(nickName);
        
        int result = userService.updateUser(user);
        return result > 0 ? Result.success("昵称更新成功") : Result.error("昵称更新失败");
    }

    /**
     * 根据用户ID获取用户信息（用于前端显示）
     */
    @GetMapping("/info/{userId}")
    public Result<Map<String, String>> getUserInfoById(@PathVariable Long userId) {
        try {
            User user = userService.selectUserById(userId);
            if (user == null) {
                return Result.error("用户不存在");
            }
            
            // 构建用户显示信息
            Map<String, String> userInfo = new HashMap<>();
            userInfo.put("userId", userId.toString());
            userInfo.put("username", user.getUsername());
            userInfo.put("nickName", user.getNickName());
            
            // 确定显示名称：优先昵称，其次用户名，最后用户ID
            String displayName;
            if (user.getNickName() != null && !user.getNickName().trim().isEmpty()) {
                displayName = user.getNickName();
            } else {
                displayName = user.getUsername();
            }
            userInfo.put("displayName", displayName);
            
            return Result.success(userInfo);
            
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取用户信息失败: " + e.getMessage());
        }
    }
}